package org.example;

import javax.swing.*;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class CSVToDatabase {
    private String csvFile;
    private String jdbcURL;
    private String username;
    private String password;
    private int columnCount;
    private String tableName;

    public CSVToDatabase(String csvFile, String jdbcURL, String username, String password, int columnCount, String tableName) {
        this.csvFile = csvFile;
        this.jdbcURL = jdbcURL;
        this.username = username;
        this.password = password;
        this.columnCount = columnCount;
        this.tableName = tableName;
    }

    public void execute() {
        try (Connection connection = DriverManager.getConnection(jdbcURL, username, password)) {
            String line;
            String[] columnNames = null;

            try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(csvFile), StandardCharsets.UTF_8))) {
                String headerLine = br.readLine();
                if (headerLine.startsWith("\uFEFF")) {
                    headerLine = headerLine.substring(1); // Remove BOM character
                }
                columnNames = headerLine.split(","); // Read the column names from the first line
                StringBuilder sqlBuilder = new StringBuilder("INSERT INTO " + tableName + " (");
                for (int i = 0; i < columnCount; i++) {
                    sqlBuilder.append(columnNames[i]);
                    if (i != columnCount - 1) {
                        sqlBuilder.append(", ");
                    }
                }
                sqlBuilder.append(") VALUES (");
                for (int i = 0; i < columnCount; i++) {
                    sqlBuilder.append("?");
                    if (i != columnCount - 1) {
                        sqlBuilder.append(", ");
                    }
                }
                sqlBuilder.append(")");
                String sql = sqlBuilder.toString();

                while ((line = br.readLine()) != null) {
                    String[] data = line.split(",");
                    if (data.length != columnCount) {
                        System.err.println("Invalid data: " + line);
                        continue;
                    }
                    try (PreparedStatement statement = connection.prepareStatement(sql)) {
                        for (int i = 0; i < columnCount; i++) {
                            // Convert the data to UTF-8
                            String utf8Data = Charset.forName("UTF-8").decode(Charset.forName("UTF-8").encode(data[i])).toString();
                            statement.setString(i + 1, utf8Data);
                        }
                        statement.executeUpdate();
                    }
                }
                System.out.println("Data has been successfully inserted into the database.");
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    // Set the Look and Feel to Nimbus
                    for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
                        if ("Nimbus".equals(info.getName())) {
                            UIManager.setLookAndFeel(info.getClassName());
                            break;
                        }
                    }
                } catch (Exception e) {
                    // If Nimbus is not available, fall back to cross-platform
                    try {
                        UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
                    } catch (Exception ex) {
                        // Not worth my time
                    }
                }

                CSVToDatabaseGUI gui = new CSVToDatabaseGUI();
                gui.setTitle("CSV表格转数据库"); // Set the title of the window
                gui.setVisible(true);
            }
        });
    }
}